package com.ruoyi.system.service.impl;

import java.io.File;
import java.math.BigDecimal;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.tencentUtils.TencentCloudImUtil;
import com.ruoyi.system.domain.AppBalanceRecord;
import com.ruoyi.system.domain.AppDynamicMsg;
import com.ruoyi.system.domain.AppTradeRecord;
import com.ruoyi.system.mapper.AppDynamicMsgMapper;
import com.ruoyi.system.service.IAppBalanceRecordService;
import com.ruoyi.system.service.IAppTradeRecordService;
import com.ruoyi.system.service.IAppUserEquipmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.AppUserMapper;
import com.ruoyi.system.domain.AppUser;
import com.ruoyi.system.service.IAppUserService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * app用户Service业务层处理
 *
 * @author ruoyi
 * @date 2023-02-27
 */
@Service
public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, AppUser> implements IAppUserService {
    @Resource
    private AppUserMapper appUserMapper;
    @Autowired
    private IAppUserEquipmentService iAppUserEquipmentService;
    @Autowired
    private TencentCloudImUtil tencentCloudImUtil;

    /**
     * 查询app用户
     *
     * @param userId app用户主键
     * @return app用户
     */
    @Override
    public AppUser selectAppUserByUserId(Long userId) {
        return appUserMapper.selectAppUserByUserId(userId);
    }

    /**
     * 查询app用户列表
     *
     * @param appUser app用户
     * @return app用户
     */
    @Override
    public List<AppUser> selectAppUserList(AppUser appUser) {
        return appUserMapper.selectAppUserList(appUser);
    }

    /**
     * 新增app用户
     *
     * @param appUser app用户
     * @return 结果
     */
    @Override
    public int insertAppUser(AppUser appUser) {
        appUser.setCreateTime(DateUtils.getNowDate());
        return appUserMapper.insertAppUser(appUser);
    }

    /**
     * 修改app用户
     *
     * @param appUser app用户
     * @return 结果
     */
    @Override
    public int updateAppUser(AppUser appUser) {
        return appUserMapper.updateAppUser(appUser);
    }

    /**
     * 批量删除app用户
     *
     * @param userIds 需要删除的app用户主键
     * @return 结果
     */
    @Override
    public int deleteAppUserByUserIds(Long[] userIds) {
        return appUserMapper.deleteAppUserByUserIds(userIds);
    }

    /**
     * 删除app用户信息
     *
     * @param userId app用户主键
     * @return 结果
     */
    @Override
    public int deleteAppUserByUserId(Long userId) {
        return appUserMapper.deleteAppUserByUserId(userId);
    }

    @Override
    public AppUser getById(Long userId) {
        return appUserMapper.selectAppUserByUserId(userId);
    }


    @Override
    public AppUser getOneByMobile(String phone) {
        AppUser appUser = new AppUser();
        appUser.setMobile(phone);
        List<AppUser> appUsers = appUserMapper.selectAppUserList(appUser);

        return appUsers.size() > 0 ? appUsers.get(0) : null;
    }

    @Override
    public AppUser getOneByMobileAndPassword(String phone, String password) {
        AppUser appUser = new AppUser();
        appUser.setMobile(phone);
        appUser.setPassword(password);
        List<AppUser> appUsers = appUserMapper.selectAppUserList(appUser);
        return appUsers.size() > 0 ? appUsers.get(0) : null;
    }

    @Override
    public int countByMobile(String phone) {
        int count = appUserMapper.countByMobile(phone);
        return count;
    }

    @Override
    public Integer findByAccount(String account) {
        return appUserMapper.findByAccount(account);
    }

    @Override
    public AjaxResult editUserInfo(AppUser user) {
        appUserMapper.updateAppUser(user);
        // 更新腾讯云IM
        AppUser userInfo = appUserMapper.selectAppUserByUserId(user.getUserId());
        tencentCloudImUtil.updataHeadUrl(userInfo.getAccount(), userInfo.getHeadImg());
        return AjaxResult.ok(0, "修改成功", user);
    }

    @Override
    public List<AppUser> listByUserIds(List<String> userIds) {
        return appUserMapper.listByUserIds(userIds);
    }

    @Override
    public List<AppUser> getListByUserIds(List<Object> userId) {
        QueryWrapper<AppUser> ew = new QueryWrapper<>();
        ew.in("user_id", userId);
        return appUserMapper.selectList(ew);
    }

    @Override
    public int updateAppUserByState(AppUser appUser) {
        return appUserMapper.updateAppUserByState(appUser);
    }

    @Override
    public int updateAppUserByPassword(AppUser appUser) {
        return appUserMapper.updateAppUserByPassword(appUser);
    }


    @Autowired
    private IAppTradeRecordService tradeRecordService;
    @Autowired
    private IAppBalanceRecordService balanceRecordService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult applyWithdrawal(Long userId, BigDecimal money, String address) {

        AppUser userEntity = this.getById(userId);
        if (money.compareTo(userEntity.getBalance()) == 1) {
            return AjaxResult.warn("余额不足");
        }
        AppTradeRecord tradeRecord = new AppTradeRecord();
        tradeRecord.setCreateTime(new Date());
        tradeRecord.setUserId(userId);
        tradeRecord.setType(1);
        tradeRecord.setAccount(address);
        tradeRecord.setMoney(money.setScale(2, BigDecimal.ROUND_HALF_UP));
        tradeRecord.setAuditType(1);

        tradeRecordService.insertAppTradeRecord(tradeRecord);

        //提现更改用户余额和待提现金额
        baseMapper.updateMoneyByApplyWithdrawal(userId, money);
        // 充值成功 添加余额记录
        AppBalanceRecord balanceRecord = new AppBalanceRecord();
        balanceRecord.setCreateTime(new Date());
        balanceRecord.setUserId(userId);
        balanceRecord.setHandle("提现");
        balanceRecord.setAmount(money.setScale(2, BigDecimal.ROUND_HALF_UP).negate());
        balanceRecord.setBalance(this.getById(userId).getBalance().setScale(2, BigDecimal.ROUND_HALF_UP));
        balanceRecordService.insertAppBalanceRecord(balanceRecord);

        return AjaxResult.ok(0, "提现申请成功", null);
    }

    @Override
    public void updateUserBalance(Long userId, BigDecimal totalBetMoney) {
        baseMapper.updateUserBalance(userId, totalBetMoney);
    }

    @Override
    public void updateUserMoneyByReceiveRedPacket(Long userId, BigDecimal receiveMoney) {
        baseMapper.updateUserMoneyByReceiveRedPacket(userId, receiveMoney);
    }

    @Override
    public AjaxResult updateUserUsdtAddress(Long userId, String collectionAddress) {
        appUserMapper.updateUserUsdtAddress(userId, collectionAddress);
        return AjaxResult.ok(0, "绑定收款成功", null);
    }

    @Override
    public void changeUserBalance(BigDecimal money, Long userId, String type, String remark) {
        // 添加纪录
        AppBalanceRecord balanceRecord = new AppBalanceRecord();
        balanceRecord.setCreateTime(new Date());
        balanceRecord.setUserId(userId);
        balanceRecord.setHandle(remark);
        if ("add".equals(type)) {
            appUserMapper.updateUserBalance(userId, money);
            balanceRecord.setAmount(money.setScale(2, BigDecimal.ROUND_HALF_UP));
        }
        if ("del".equals(type)) {
            appUserMapper.updateMoneyByApplyWithdrawal(userId, money);
            balanceRecord.setAmount(money.setScale(2, BigDecimal.ROUND_HALF_UP).negate());
        }
        balanceRecord.setBalance(this.getById(userId).getBalance().setScale(2, BigDecimal.ROUND_HALF_UP));
        balanceRecordService.insertAppBalanceRecord(balanceRecord);
    }
}
